<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品库存" prop="inventory">
        <el-input
          v-model="queryParams.inventory"
          placeholder="请输入商品库存"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择商品类型" clearable size="small">
          <el-option
            v-for="dict in commodityTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择商品状态" clearable size="small">
          <el-option
            v-for="dict in commodityStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['commodity:commodity:add']"
        >新增商品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAddCoupon"
          v-hasPermi="['commodity:commodity:add']"
        >导入优惠券</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['commodity:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['commodity:commodity:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          :loading="exportLoading"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['commodity:commodity:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="commodityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="商品图片" align="center" prop="imgUrl" >
        <template slot-scope="scope">
          <el-image v-if="scope.row.imgUrl"
                    style="width: 100px; height: 50px;border-radius: 10%;"
                    :src="scope.row.imgUrl">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品价格" align="center" prop="price" />
      <el-table-column label="商品原价" align="center" prop="originalPrice" />
      <el-table-column label="商品明细" align="center" prop="detail" />
      <el-table-column label="优惠券面值" align="center" prop="nominal" />
      <el-table-column label="商品库存" align="center" prop="inventory" />
      <el-table-column label="商品类型" align="center" prop="type"  :formatter="typeFormat"/>
      <el-table-column label="商品状态" align="center" prop="status" :formatter="statusFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['commodity:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['commodity:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

<!--    <el-dialog title="导入优惠券" :visible.sync="openCoupon" width="1200px" append-to-body>-->
<!--      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">-->


<!--        <el-form-item label="优惠券类型" prop="type">-->
<!--          <el-select v-model="queryCouponParams.type" placeholder="请选择类型" clearable size="small" style="width:120px;">-->
<!--            <el-option label="全部" value="" />-->
<!--            <el-option-->
<!--              v-for="dict in typeOptions"-->
<!--              :key="dict.dictValue"-->
<!--              :label="dict.dictLabel"-->
<!--              :value="dict.dictValue"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="优惠券名称" prop="name">-->
<!--          <el-input-->
<!--            v-model="queryCouponParams.name" style="width:150px;"-->
<!--            placeholder="请输入名称"-->
<!--            clearable-->
<!--            size="small"-->
<!--            @keyup.enter.native="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryCoupon">搜索</el-button>-->
<!--          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <el-table  :data="couponList" @selection-change="handleSelectionChange">-->
<!--        &lt;!&ndash; <el-table-column type="selection" width="55" align="center" /> &ndash;&gt;-->
<!--        <el-table-column label="类型" align="left" prop="type" >-->
<!--          <template slot-scope="scope">-->
<!--            {{selectDictLabel(typeOptions, scope.row.type)}}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="优惠方式" align="left" prop="dtype" >-->
<!--          <template slot-scope="scope">-->
<!--            {{selectDictLabel(dtypeOptions, scope.row.dtype)}}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="名称" align="left" prop="name"  />-->
<!--        <el-table-column label="总数量" align="center" prop="total" />-->
<!--        <el-table-column label="金额/折扣" align="center" prop="discount" >-->
<!--          <template slot-scope="scope">-->
<!--            {{scope.row.dtype == 1 ? '￥' + scope.row.discount : scope.row.discount + '%'}}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="最少消费" align="center" prop="min" />-->
<!--        <el-table-column label="最高抵扣" align="center" prop="max" />-->
<!--&lt;!&ndash;        <el-table-column label="限制数量" align="center" prop="limits" />&ndash;&gt;-->
<!--        <el-table-column label="开始时间" align="center" prop="startTime" width="120">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="截至时间" align="center" prop="endTime" width="120">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->

<!--        <el-table-column label="创建时间" align="center" prop="createTime" width="160">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.createTime) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">-->
<!--          <template slot-scope="scope">-->
<!--            <el-button-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              icon="el-icon-edit"-->
<!--              @click="addCoupon(scope.row)"-->
<!--            >导入</el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--      </el-table>-->
<!--      <pagination-->
<!--        v-show="couponTotal>0"-->
<!--        :total="couponTotal"-->
<!--        :page.sync="queryCouponParams.pageNum"-->
<!--        :limit.sync="queryCouponParams.pageSize"-->
<!--        @pagination="getCouponList"-->
<!--      />-->
<!--    </el-dialog>-->
    <!-- 添加或修改商品
对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择商品类型">
            <el-option
              v-for="dict in commodityTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value=parseInt(dict.dictValue)
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="name" v-show="form.type===1">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品图片" prop="imgUrl" v-show="form.type===1">
          <ImageUpload v-model="form.imgUrl"/>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入商品价格" />
        </el-form-item>
        <el-form-item label="商品原价" prop="originalPrice" v-show="form.type===1">
          <el-input v-model="form.originalPrice" placeholder="请输入商品原价" />
        </el-form-item>
        <el-form-item label="商品明细" prop="detail">
          <el-input v-model="form.detail"type="textarea" placeholder="请输入商品明细" />
        </el-form-item>
<!--        <el-form-item label="优惠券面值" prop="nominal" v-show="form.type===2">-->
<!--          <el-input v-model="form.nominal" placeholder="请输入优惠券面值" />-->
<!--        </el-form-item>-->
        <el-form-item label="商品库存" prop="inventory" v-show="form.type===1">
          <el-input v-model="form.inventory" placeholder="请输入商品库存" />
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select v-model="form.status" placeholder="请选择商品状态" >
            <el-option
              v-for="dict in commodityStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value=parseInt(dict.dictValue)
            />
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="选择优惠券" prop="couponId" v-show="form.type===2 && form.name===null">
              <el-transfer filterable v-model="distCouponList"
                           :titles="['可选优惠券','已选优惠券']"
                           :data="couponList"></el-transfer>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-show="form.type===1"> 确 定</el-button>
        <el-button type="primary" @click="submitForm1" v-show="form.type===2">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCommodity, getCommodity, delCommodity, addCommodity, updateCommodity, exportCommodity } from "@/api/commodity/commodity";
import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon, exportCoupon } from "@/api/business/coupon";
import ImageUpload from '@/components/ImageUpload';
export default {
  name: "Commodity",
  components: {
    ImageUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      couponTotal: 0,
      // 商品表格数据
      commodityList: [],
      distCouponList: [],
      couponList:[],
      coupon :null,
      //字典数据
      commodityTypeOptions: [],
      commodityStatusOptions: [],
      typeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openCoupon: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        couponId: null,
        name: null,
        imgUrl: null,
        price: null,
        originalPrice: null,
        detail: null,
        nominal: null,
        inventory: null,
        type: null,
        status: null
      },
      queryCouponParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        descr: null,
        tag: null,
        total: null,
        discount: null,
        min: null,
        limits: null,
        type: null,
        status: null,
        share: null,
        cateType: null,
        code: null,
        timeType: null,
        days: null,
        startTime: null,
        endTime: null,
        areaCode: null
      },
      // 表单参数
      form: {
        couponId: null,
        name: null,
        nominal: null,
        inventory: null
      },
      // 表单校验
      rules: {
        // name: [
        //   { required: true, message: "商品名称不能为空", trigger: "blur" }
        // ],
        status: [
          { required: true, message: "商品状态，1：可用；0:不可用不能为空", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    // // 计算属性的 getter
    // detail: function () {
    //     return "满" + this.form.price+ "积分可兑换"
    // },

  },
  created() {
    this.getList();
    this.getDicts("tb_commodity_type").then(response => {
      this.commodityTypeOptions = response.data;
    });
    this.getDicts("tb_commodity_status").then(response => {
      this.commodityStatusOptions = response.data;
    });
    this.getDicts("tb_coupon_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("tb_coupon_share").then(response => {
      this.shareOptions = response.data;
    });
    this.getDicts("tb_coupon_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("tb_coupon_dtype").then(response => {
      this.dtypeOptions = response.data;
    });
  },
  methods: {
    /** 查询商品
     列表 */
    getList() {
      this.loading = true;
      listCommodity(this.queryParams).then(response => {
        this.commodityList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getCoupon(){
      const couponId =parseInt(this.distCouponList.join())
      getCoupon(couponId).then(response => {
        console.log(response.data.name)
        this.queryParams.couponId=response.data.id
        this.queryParams.name=response.data.name
        this.queryParams.nominal=response.data.discount
        this.queryParams.inventory=response.data.total
        //console.log( this.queryParams)
      });
    },
    getCouponList() {
      this.queryCouponParams.status=0;
      this.queryCouponParams.type=5;
      listCoupon(this.queryCouponParams).then(response => {
        this.couponList = response.rows.map(a =>{
          return{
            key: a.id,
            label: a.name
          }
        });
        if(this.form.couponList){
          this.distCouponList = this.form.couponList.map(a=>{
            return  a.id
          })
        } else {
          this.distCouponList = []
        }
      });
    },

    handleAddCoupon(){
      this.openCoupon=true;
      this.getCouponList()
    },
    addCoupon(row){
      this.queryParams.couponId=row.id
      this.queryParams.name=row.name
      this.queryParams.nominal=row.discount
      this.queryParams.inventory=row.total
      this.queryParams.type=2
      addCommodity(this.queryParams).then(response => {
        this.openCoupon = false;
        this.getList();
      })
    },
    /** 搜索按钮操作 */
    handleQueryCoupon() {
      this.queryCouponParams.pageNum = 1;
      this.getCouponList()
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        couponId: null,
        name: null,
        imgUrl: null,
        price: null,
        originalPrice: null,
        detail: "满积分可兑换",
        nominal: null,
        inventory: null,
        type: null,
        createTime: null,
        status: 1
      };
      this.resetForm("form");
    },


    // 商品类型字典翻译
    typeFormat(row) {
      return this.selectDictLabel(this.commodityTypeOptions, row.type);
    },
    // 商品状态字典翻译
    statusFormat(row) {
      return this.selectDictLabel(this.commodityStatusOptions, row.status);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.handleQueryCoupon();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
      this.getCouponList()
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCommodity(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交商品按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCommodity(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCommodity(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交优惠券按钮 */
    submitForm1() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCommodity(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
              const couponId =parseInt(this.distCouponList.join())
              getCoupon(couponId).then(response => {
                this.form.couponId=response.data.id
                this.form.name=response.data.name
                this.form.nominal=response.data.discount
                this.form.inventory=response.data.total
                addCommodity(this.form).then(response => {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              });
          }
        }
      });
    },


    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const name = row.name
      this.$confirm('是否删除商品"' + name + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
    }).then(function() {
  return delCommodity(ids);
}).then(() => {
  this.getList();
  this.msgSuccess("删除成功");
})
},
/** 导出按钮操作 */
handleExport() {
  const queryParams = this.queryParams;
  this.$confirm('是否确认导出所有商品数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
}).then(() => {
  this.exportLoading = true;
  return exportCommodity(queryParams);
}).then(response => {
  this.download(response.msg);
  this.exportLoading = false;
})
}
}
};
</script>
